#include "checkboxes.h"
#include <QStandardItemModel>
#include <QComboBox>
#include <QList>
#include <QSqlQuery>
#include <qplugin.h>
#include <QDebug>

CheckBoxes::CheckBoxes()
{
}

QWidget *CheckBoxes::createDelegate(const QVariantMap &properties)
{
    QComboBox *box = new QComboBox;
    QList<QStandardItem *> items;
    if (properties.contains("table")) {
        QString table = properties["table"].toString();
        QString nameField = properties["name_field"].toString();

        QSqlQuery sql;
        sql.exec(QString("SELECT `id`,`%1` FROM `%2` WHERE 1;").arg(nameField).arg(table));

        while (sql.next()) {
            QVariant id = sql.value(0);
            QString name = sql.value(1).toString();

            QStandardItem* item = new QStandardItem(name);
            item->setData(id, Qt::UserRole + 1);
            item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
            item->setData(Qt::Unchecked, Qt::CheckStateRole);

            items.append(item);
        }
    }
    QStandardItemModel *model = new QStandardItemModel(items.count(), 1); // 3 rows, 1 col
    model->insertColumn(0, items);
    box->setModel(model);

    return box;
}

void CheckBoxes::setEditable(QWidget *delegate, bool editable)
{
    QComboBox *edit = (QComboBox *)delegate;
    edit->setEnabled(editable);
}

QVariant CheckBoxes::data(QWidget *delegate) const
{
    QComboBox *edit = (QComboBox *)delegate;

    int count = edit->model()->rowCount();
    QStringList list;
    for (int i = 0; i < count; ++i) {
        if (edit->itemData(i, Qt::CheckStateRole) == Qt::Checked) {
            list << edit->itemData(i, Qt::UserRole + 1).toString();
            qDebug() << edit->itemData(i, Qt::UserRole + 1).toString();
        }
    }
    return list.join(";");
}

void CheckBoxes::setData(QWidget *delegate, const QVariant &data)
{
    QComboBox *edit = (QComboBox *)delegate;

    int count = edit->model()->rowCount();
    for (int i = 0; i < count; ++i)
            edit->setItemData(i, Qt::Unchecked, Qt::CheckStateRole);

    QStringList list = data.toString().split(';', QString::SkipEmptyParts);
    for (int i = 0; i < list.count(); ++i) {
        int id = list[i].toInt();
        int idx = edit->findData(id, Qt::UserRole + 1);

        if (idx >= 0)
            edit->setItemData(idx, Qt::Checked, Qt::CheckStateRole);
    }
}

void CheckBoxes::clear(QWidget *delegate)
{
    QComboBox *edit = (QComboBox *)delegate;
    int count = edit->model()->rowCount();
    for (int i = 0; i < count; ++i)
            edit->setItemData(i, Qt::Unchecked);
}

Q_EXPORT_PLUGIN2(checkboxes-field, CheckBoxes)
